<template>
    <view class="wrap">
        <!-- 云游相册和本地相册 -->
        <view class="tabs-wrap" style="width: 440rpx;">
            <u-tabs ref="tabs" :list="list" :current="current" bar-height="6" bar-width="40" active-color="#20bf64" @change="change"></u-tabs>
        </view>
        <!-- 图片列表 -->
        <view class="list-wrap">
            <view class="list" :class="{ move: current == 1 }" v-for="(item, index) in allPhotosList" :key="index">
                <view class="item add-photo" v-if="current === 1" @click="choosePhoto">
                    <image class="cover-image" src="../static/selectPhoto/add-photo-icon.png" mode=""></image>
                    <view class="">更多照片</view>
                </view>
                <view v-for="(item2, index2) in item" :key="index2" class="item">
                    <LazyImage class="cover-image" :src="item2.image_url_t" mode="aspectFill" :imageStyle="imageStyle"></LazyImage>
                    <view class="select-circle" :class="{ selected: item2.isSelected }" @click="toggleSelected(item2)">{{ item2.isSelected ? item2.selectedIndex : '' }}</view>
                </view>
            </view>
        </view>
        <!--  -->
        <view class="bottom-wrap">
            <view class="select-photo-wrap" v-if="hadSelectedPhotosAmout > 0"><SelectedList :photosList="selectedPhotosList" @delectPhoto="delectPhoto"></SelectedList></view>
            <view class="default-box">
                <view class="">可选择1 - {{ maxPhotosAmout }}张照片</view>
                <view class="btn active" v-if="hadSelectedPhotosAmout > 0" @click="sure">确定({{ hadSelectedPhotosAmout }})</view>
                <view class="btn" v-else>确定</view>
            </view>
        </view>
    </view>
</template>
<script>
import { uploadFile, flatten } from '@/common/utils.js';
import { getItemIndex } from '@/common/common.js';
import { getAlbumPhotoes } from '@/api/photos.js';
import SelectedList from '../components/SelectedList.vue';
import LazyImage from '@/components/LazyImage/index.vue';
export default {
    name: '',
    data() {
        return {
            list: [
                {
                    name: '云游相册'
                },
                {
                    name: '本地相册'
                }
            ],
            current: 0,
            // 已经选了几张照片
            hadSelectedPhotosAmout: 0,
            // 已经选择的照片
            selectedPhotosList: [],
            // 上传成功数量
            uploadSuccessAmount: 0,
            // 上传失败数量
            uploadErrorAmount: 0,
            //从相册中选取的照片
            photosFromAlbum: [],
            // 云游相册和本地相册所有数据
            allPhotosList: [[], []],
            imageStyle: {
                width: '100%',
                height: '100%',
                borderRadius: '10rpx'
            }
        };
    },
    props: {
        maxPhotosAmout: {
            type: Number,
            default: 1
        },
        isAddPhoto: {
            type: Boolean,
            default: false
        }
    },
    created() {
        this.selectedPhotosList = this.vuex_selectedPhotosList;
        this.hadSelectedPhotosAmout = this.selectedPhotosList.length;
        this.getAlbumPhotoes();
    },
    methods: {
        change(index) {
            this.current = index;
        },
        // 获取被选中的图片的index
        getSelectedIndex(item, arr) {
            if (arr.length <= 0) {
                return 0;
            }
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].albumid === item.albumid) {
                    return arr[i].selectedIndex;
                }
            }
        },
        // 获取相册数据
        async getAlbumPhotoes() {
            let list = await getAlbumPhotoes();
            if (list && list.length > 0) {
                let tempList = flatten(list, 'photos');
                // 增加一个临时变量 保证数据的一致性
                let selectedList = [];
                tempList.forEach((item, index) => {
                    item.isSelected = false;
                    item.selectedIndex = 0;
                    let selectedIndex = this.getSelectedIndex(item, this.selectedPhotosList);
                    if (selectedIndex > 0) {
                        item.isSelected = true;
                        item.selectedIndex = selectedIndex;
                        selectedList.push(item);
                    }
                });
                this.selectedPhotosList = selectedList;
                this.allPhotosList.splice(0, 1, tempList);
            }
        },
        //切换选中和非选中
        toggleSelected(item) {
            if (!item.isSelected && this.hadSelectedPhotosAmout >= this.maxPhotosAmout) {
                this.$showToast(`您最多只能选择${this.maxPhotosAmout}涨照片`);
                return;
            }
            if (item.isSelected && this.hadSelectedPhotosAmout <= 1 && this.isAddPhoto) {
                this.$showToast('请至少保留一张照片');
                return;
            }
            item.isSelected = !item.isSelected;
            if (item.isSelected) {
                this.selectedPhotosList.push(item);
            } else {
                let index = getItemIndex(this.selectedPhotosList, item, 'albumid');
                this.selectedPhotosList.splice(index, 1);
            }
            this.hadSelectedPhotosAmout = this.selectedPhotosList.length;
            this.selectedPhotosList.forEach((item, index) => {
                item.selectedIndex = index + 1;
            });
        },
        // 删除选中
        delectPhoto(item) {
            if (this.hadSelectedPhotosAmout <= 1 && this.isAddPhoto) {
                this.$showToast('请至少保留一张照片');
                return;
            }
            let index = getItemIndex(this.selectedPhotosList, item, 'albumid');
            this.selectedPhotosList[index].isSelected = false;
            this.selectedPhotosList.splice(index, 1);
            this.hadSelectedPhotosAmout = this.selectedPhotosList.length;
            this.selectedPhotosList.forEach((item, index) => {
                item.selectedIndex = index + 1;
            });
            this.$u.vuex('vuex_selectedPhotosList', this.selectedPhotosList);
        },
        // 从相册选取相片
        async choosePhoto() {
            if (this.hadSelectedPhotosAmout >= this.maxPhotosAmout) {
                this.$showToast(`您最多只能选择${this.maxPhotosAmout}涨照片`);
                return;
            }
            let photo = await this.$uniPromise.chooseImage({ count: this.maxPhotosAmout - this.hadSelectedPhotosAmout });
            photo && photo.tempFilePaths.length > 0 && this.startUpload(photo.tempFilePaths);
        },
        // 开始上传照片
        startUpload(list) {
            setTimeout(() => {
                this.$showLoading();
            }, 500);
            let photosLength = list.length;
            list.forEach((item, index) => {
                uploadFile(`${this.$config.baseUrl}/api/upload/obs`, item, this.$config.tokenKey, {}, true)
                    .then(res => {
                        if (res.RequestStatus === 100 && res.Data) {
                            this.addPhotoToAlbumList(res.Data);
                            this.uploadSuccessAmount += 1;
                        } else {
                            this.uploadErrorAmount += 1;
                        }
                        this.checkUploadEnd(photosLength);
                    })
                    .catch(err => {
                        this.uploadErrorAmount += 1;
                        this.checkUploadEnd(photosLength);
                    });
            });
        },
        // 增加图片到相册列表
        addPhotoToAlbumList(data) {
            data.isSelected = true;
            data.selectedIndex = this.selectedPhotosList.length + 1;
            this.allPhotosList[1].push(data);
            this.selectedPhotosList.push(data);
        },
        //判断是否全部上传完成
        checkUploadEnd(length) {
            if (this.uploadSuccessAmount + this.uploadErrorAmount >= length) {
                this.$hideLoading();
                this.$showToast(`上传成功${this.uploadSuccessAmount}张,上传失败${this.uploadErrorAmount}张`);
                this.uploadSuccessAmount = this.uploadErrorAmount = 0;
                this.hadSelectedPhotosAmout = this.selectedPhotosList.length;
            }
        },
        // 上传完成
        sure() {
            this.$u.vuex('vuex_selectedPhotosList', this.selectedPhotosList);
            this.$emit('sure');
        }
    },
    watch: {},
    components: { SelectedList, LazyImage }
};
</script>
<style lang="scss" scoped>
.wrap {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100vh;
    max-height: 100vh;
    .tabs-wrap {
        width: 100%;
        position: relative;
        flex-shrink: 0;
        &::after {
            position: absolute;
            content: '';
            left: 0;
            bottom: 4rpx;
            content: '';
            width: 750rpx;
            height: 2rpx;
            background: #e9eef3;
        }
    }
    .list-wrap {
        width: 100%;
        flex-grow: 9;
        padding: 30rpx 0 0 30rpx;
        box-sizing: border-box;
        display: flex;
        overflow-y: scroll;
        overflow-x: hidden;

        .list {
            align-items: flex-start;
            display: flex;
            flex-wrap: wrap;
            flex-shrink: 0;
            width: 100%;
            height: 240rpx;
            transition: all 0.5s ease;
            transform: translateX(0);
            .item {
                position: relative;
                flex-shrink: 0;
                width: 210rpx;
                height: 140rpx;
                border-radius: 10rpx;
                margin: 0 30rpx 30rpx 0;
                .cover-image {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: 100%;
                    border-radius: 10rpx;
                    z-index: 0;
                }
                .select-circle {
                    position: absolute;
                    right: 10rpx;
                    top: 10rpx;
                    width: 32rpx;
                    height: 32rpx;
                    background-color: #000000;
                    border: solid 2rpx #ffffff;
                    box-sizing: border-box;
                    border-radius: 100%;
                    z-index: 11;
                    &::after {
                        position: absolute;
                        content: '';
                        left: 50%;
                        top: 50%;
                        width: 200%;
                        height: 200%;
                        transform: translate(-50%, -50%);
                    }
                }
                .selected {
                    position: absolute;
                    background-image: linear-gradient(45deg, #6dc35a 0%, #7bcf6b 100%), linear-gradient(#000000, #000000);
                    box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(18, 28, 81, 0.05);
                    border: solid 2rpx #ffffff;
                    font-size: 22rpx;
                    color: #ffffff;
                    line-height: 22rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
            }
            .add-photo {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                border-radius: 10rpx;
                border: dashed 2rpx #c4cad6;
                color: #c4cad6;
                font-size: 22rpx;
                line-height: 22rpx;
                .cover-image {
                    position: relative;
                    width: 44rpx;
                    height: 36rpx;
                    margin-bottom: 14rpx;
                }
            }
        }
        .move {
            transform: translateX(-100%);
        }
    }
    .bottom-wrap {
        width: 750rpx;
        flex-shrink: 0;
        background-color: #ffffff;
        box-shadow: 0rpx -6rpx 40rpx 0rpx rgba(0, 0, 0, 0.05);
        .default-box {
            color: #abb3b8;
            padding: 30rpx 18rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 26rpx;
            line-height: 26rpx;
            .btn {
                width: 200rpx;
                height: 66rpx;
                background-color: #d6d6d6;
                border-radius: 10rpx;
                font-size: 30rpx;
                color: #fff;
                line-height: 30rpx;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .active {
                background-image: linear-gradient(45deg, #4dc450 0%, #5fd062 100%), linear-gradient(#31bd71, #31bd71);
            }
        }
        .select-photo-wrap {
            padding-bottom: 30rpx;
            width: 100%;
            box-sizing: border-box;
            border-bottom: 1rpx solid #e9eef3;
        }
    }
}
</style>
